<template>
  <div class="PermissionBgc">
    <!-- 添加权限按钮 -->
    <div class="ChaHeader">
      <el-button type="primary" class="addCharactor" @click="formShow = true"
        >添加权限</el-button
      >
    </div>
    <!-- 展示界面 -->
    <div class="tree-box">
      <div class="tree-nav">
        <div class="item">权限名称</div>
        <div class="item">权限描述</div>
        <div class="item">外部资源链接</div>
        <div class="item">操作</div>
      </div>
      <div class="tree-content">
        <el-tree
          ref="tree"
          :data="assignData"
          node-key="resourceId"
          :props="props"
          default-expand-all
          :expand-on-click-node="false"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <template>
              <div class="node_div">
                <span class="name-box">
                  {{ node.label }}
                </span>
                <span class="size-box">
                  {{ data.resourceDesc }}
                </span>
                <span class="secret-box">
                  {{ data.url }}
                </span>
                <span class="operate-box">
                  <alter-button
                    type="text"
                    size="medium"
                    class="el-icon-edit"
                    @click="Edite(node, data), (editeFormShow = true)"
                  ></alter-button>
                  <alter-button
                    type="text"
                    size="medium"
                    class="el-icon-delete"
                    @click="Delete(node, data), open()"
                  ></alter-button>
                </span>
              </div>
            </template>
          </span>
        </el-tree>
      </div>
    </div>
    <!-- 添加权限 -->
    <div class="SpringFrame" v-show="formShow">
      <div class="form">
        <i class="el-icon-close" id="close" @click="close()"></i>
        <f-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <form-item label="权限Id" prop="resourceId" class="objectName">
            <!-- <form-input
              v-model="ruleForm.resourceId"
              name="resourceId"
            ></form-input> -->
            <el-cascader
              ref="cascader"
              :options="permissionOptions"
              :props="permissionProps"
              :show-all-levels="false"
              v-model="ruleForm.resourceId"
              name="resourceId"
            >
              <template slot-scope="{ node, data }">
                <div @click="cascaderClick(data)">
                  <span>{{ node.label }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </div>
              </template>
            </el-cascader>
          </form-item>
          <form-item label="权限名称" prop="resourceName">
            <form-input
              v-model="ruleForm.resourceName"
              name="resourceName"
            ></form-input>
          </form-item>
          <form-item label="权限描述" prop="resourceDesc" class="described">
            <form-input
              type="textarea"
              v-model="ruleForm.resourceDesc"
              name="resourceDesc"
              resize="none"
            ></form-input>
          </form-item>
          <form-item label="外部资源链接" prop="url">
            <form-input v-model="ruleForm.url" name="url"></form-input>
          </form-item>
          <form-item class="operateBtn">
            <msg-button @click="resetForm('ruleForm')">重置</msg-button>
            <msg-button type="primary" @click="submitForm('ruleForm')"
              >添加</msg-button
            >
          </form-item>
        </f-form>
      </div>
    </div>
    <!-- 编辑角色表单 -->
    <div class="SpringFrame" v-show="editeFormShow">
      <div class="editTable">
        <f-form
          ref="form"
          :model="sizeForm"
          label-width="80px"
          size="medium"
          class="editForm"
          @submit.native.prevent
        >
          <form-item label="权限名称" prop="resourceName">
            <form-input
              v-model="sizeForm.resourceName"
              name="resourceName"
            ></form-input>
          </form-item>
          <form-item label="权限描述" prop="resourceDesc">
            <form-input
              type="textarea"
              v-model="sizeForm.resourceDesc"
              name="resourceDesc"
              resize=none
            ></form-input>
          </form-item>
          <form-item label="链接" prop="url">
            <form-input v-model="sizeForm.url" name="url"></form-input>
          </form-item>
          <form-item size="large" class="roleBtn">
            <alter-button type="primary" @click="onSubmit()">修改</alter-button>
            <alter-button @click="cancle">取消</alter-button>
          </form-item>
        </f-form>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import {AddAuthorityAPI,UpdateAuthorityAPI,DeleteAuthAPI,GetAllAuthorityAPI} from '@/api/utils'
export default {
  inject: ["reload"],
  data() {
    return {
      formShow: false,
      editeFormShow: false,
      addrCode: undefined,
      permissionOptions: [],
      permissionProps: {
        label: "resourceName",
        value: "resourceId",
        checkStrictly: true,
        expandTrigger: "hover",
        emitPath: false,
      },
      // 表单配置
      ruleForm: {
        resourceId: "",
        resourceName: "",
        resourceDesc: "",
        url: "",
      },
      rules: {
        resourceId: [
          {
            required: true,
            min: 3,
            message: "长度应为3的倍数",
            trigger: "blur",
          },
        ],
        resourceName: [
          { required: true, message: "请输入权限名称", trigger: "blur" },
        ],
      },
      assignData: [],
      props: {
        // 配置选项
        children: "children",
        label: "resourceName",
      },
      sizeForm: {
        resourceName: "",
        resourceDesc: "",
        url: "",
      },
      currentId: 0,
    };
  },
  methods: {
    // 关闭增加权限表单
    close() {
      this.formShow = false;
    },
    //增加方法
    async submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //获取所有的表单中的内容
          var params = $(".demo-ruleForm").serializeArray();
          //    console.log(params);
          //把从表单获取过来的值存储为对象
          let array = {};
          array["parentId"] = this.addrCode;
          params.forEach((element) => {
            array[element.name] = element.value;
          });
          //把对象转换为 jsonp 格式
          array = JSON.stringify(array);
          return AddAuthorityAPI(array).then(res=>{
            if (res.data.flag) {
              this.formShow = false;
              this.reload();
              this.$message.success("增加权限成功!");
            } else {
              this.$message.error("增加权限失败!");
            }
          })
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 权限的编辑
    Edite(node, data) {
      this.editeFormShow = true;
      this.sizeForm.resourceName = data.resourceName;
      this.sizeForm.resourceDesc = data.resourceDesc;
      this.sizeForm.url = data.url;
      this.currentId = data.resourceId;
    },
    //权限编辑的提交
    async onSubmit() {
      var params = $(".editForm").serializeArray();
      let array = {};
      array.resourceId = this.currentId;
      //判断表单不能为空，且获取到数据
      params.forEach((element) => {
        array[element.name] = element.value;
      });
      //把对象转换为 jsonp 格式
      array = JSON.stringify(array);
      // console.log(array);
      // 进行修改操作
      return UpdateAuthorityAPI(array).then(res=>{
        if (res.data.flag) {
          this.editeFormShow = false;
          this.reload();
          this.$message.success("修改成功！");
        } else {
          this.$message.error(res.data.errorMsg);
        }
      })
    },
    //取消
    cancle() {
      this.editeFormShow = false;
    },
    // 删除按钮判断
    open() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ExecuteDelete();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
          this.reload();
        });
    },
    // 权限的删除
    Delete(note, data) {
      this.currentId = data.resourceId;
    },
    //删除执行
    async ExecuteDelete() {
      return DeleteAuthAPI(this.currentId).then(res=>{
         if (res.data.flag) {
            this.reload();
            this.$message.success("删除成功！");
          } else {
            this.$message.error(res.data.errorMsg);
          }
      })
    },
    //级联选择器
    cascaderClick(nodeData) {
      this.addrCode = nodeData.resourceId;
      this.$refs.cascader.checkedValue = nodeData.resourceId;
      this.$refs.cascader.computePresentText();
      this.$refs.cascader.toggleDropDownVisible(false);
      this.$message({
        message: "已选择：" + nodeData.resourceName,
        type: "success",
        duration: 1000,
      });
    },
  },
  async mounted() {
    const res = await GetAllAuthorityAPI()
    if (res.data.flag) {
          var getAllassign = res.data.data;
          // console.log(getAllassign);
          // 把获取过来的数组转换成可渲染的数组
          getAllassign.forEach((e) => {
            // console.log(e.resourceName,e.parentId.length);
            if (e.parentId == "-1") {
              e["children"] = [];
              this.assignData.push(e);
              // console.log(this.assignData);
            } else if (e.resourceId.length == 3) {
              this.assignData.forEach((element) => {
                if (element.resourceId === e.parentId) {
                  e["children"] = [];
                  element.children.push(e);
                }
              });
            } else if (e.resourceId.length == 6) {
              this.assignData.forEach((element) => {
                element.children.forEach((el) => {
                  if (el.resourceId === e.parentId) {
                    e["children"] = [];
                    el.children.push(e);
                  }
                });
              });
            } else {
              this.assignData.forEach((element) => {
                element.children.forEach((ele) => {
                  ele.children.forEach((el) => {
                    if (el.resourceId === e.parentId) {
                      el.children.push(e);
                    }
                  });
                });
              });
            }
          });
        } else {
          this.$message.error("权限查询失败！");
        }
    this.permissionOptions = this.assignData;
  },
};
</script>

<style scoped lang="less">
.PermissionBgc {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .addCharactor {
    margin-bottom: 20px;
  }
  .tree-box {
    position: relative;
    height: 100%;
    font-weight: 700;
    .tree-nav {
      width: 100%;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #e6e6e6;
      padding: 12px 0;
      .item {
        font-size: 14px;
        color: #666;
        text-align: center;
        &:nth-child(1) {
          width: 300px;
          text-align: left;
          padding-left: 25px;
        }
        &:nth-child(2),
        &:nth-child(3),
        &:nth-child(4) {
          flex: 0 0 310px;
        }
      }
    }
    .tree-content {
      /deep/.el-tree-node__content {
        margin-top: 15px;
        background-color: transparent;
        .el-icon-caret-right::before{
          color:#409eff;
        }
      }
      /deep/.el-tree-node {
        background-color: transparent !important;
      }
      /deep/.el-tree {
        background-color: transparent;
      }
      .custom-tree-node {
        width: 100%;
        font-size: 14px;
        .node_div {
          display: flex;
          align-items: center;
          span {
            text-align: center;
            &.name-box {
              width: 375px;
              text-align: left;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }
          .size-box,
          .secret-box {
            flex: 0 0 268px;
            text-align: left;
          }
          .operate-box {
            // margin-top: 10px;
            flex: 0 0 300px;
            text-align: center;
          }
        }
      }
    }
  }
  .form,
  .editTable {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 670px;
    max-height: 650px;
    background-color: white;
    padding-left: 135px;
    padding-top: 30px;
    box-sizing: border-box;
    border-radius: 15px;
    /deep/form input {
      margin: -3px;
    }
    /deep/.el-form demo-ruleForm {
      width: 450px;
      height: 500px;
    }
    /deep/.el-form-item__content {
      width: 300px;
    }
    #close {
      position: absolute;
      top: 5px;
      right: 5px;
      font-size: 20px;
      cursor: pointer;
      color: #ccc;
    }
    .described {
      /deep/.el-textarea__inner {
        min-height: 88px !important;
      }
    }
    .operateBtn,
    .roleBtn {
      margin-left: 30px;
    }
  }
}
</style>